package com.shuyun.springdata.showcase.controller;

import com.shuyun.springdata.showcase.domain.Person;
import com.shuyun.springdata.showcase.repository.PersonRepository;
import com.shuyun.springdata.showcase.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * Created by feng.ding on 2017/1/6.
 */
@RestController
public class PersonController {

    @Autowired
    private PersonRepository personRepository;

    @Autowired
    private PersonService personService;

    @RequestMapping("/save")
    public Person save(String name, String address, int age){
        return personRepository.save(new Person(null, name, age, address));
    }

    @RequestMapping("/q1")
    public List<Person> q1(String address){
        return personRepository.findByAddress(address);
    }


    @RequestMapping("/q2")
    public Person q2(String name, String address){
        return personRepository.findByNameAndAddress(name, address);
    }

    @RequestMapping("/q3")
    public Person q3(String name, String address){
        return personRepository.withNameAndAddressQuery(name, address);
    }

    @RequestMapping("/q4")
    public Person q4(String name, String address){
        return personRepository.withNameAndAddressNamedQuery(name, address);
    }

    @RequestMapping("/sort")
    public List<Person> sort(){
        return personRepository.findAll(new Sort(Sort.Direction.ASC,  "age"));
    }

    @RequestMapping("/page")
    public Page<Person> page(){
        return personRepository.findAll(new PageRequest(1, 2));
    }

    /*@RequestMapping("/auto")
    public Page<Person> auto(Person person){
        return personRepository.findByAuto(person, new PageRequest(0, 10));
    }*/

    @RequestMapping("/rollback")
    public Person rollback(Person person){
        return personService.savePersonWithRollBack(person);
    }

    @RequestMapping("/norollback")
    public Person norollback(Person person){
        return personService.savePersonWithoutRollBack(person);
    }
}
